
觀察 index-Start.html 可以發現有三個 input 分別控制顏色、模糊度、寬度
<h2>Update CSS Variables with <span class="hl">JS</span></h2>
<div class="controls">
  <label for="spacing">Spacing:</label>
  <input
    id="spacing"
    type="range"
    name="spacing"
    min="10"
    max="200"
    value="10"
    data-sizing="px"
  />
  <label for="blur">Blur:</label>
  <input
    id="blur"
    type="range"
    name="blur"
    min="0"
    max="25"
    value="10"
    data-sizing="px"
  />
  <label for="base">Base Color</label>
  <input id="base" type="color" name="base" value="#ffc600" />
</div>
<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500" />
在看影片之前,我先使用了前兩天所學的渾身解數完成了這題,完成是完成了但發現根本沒學到今天題目的重點 CSS Variables。
const spacingControl = document.querySelector("input#spacing");
const blurControl = document.querySelector("input#blur");
const colorControl = document.querySelector("input#base");
const imgContainer = document.querySelector("img");
const hl = document.querySelector(".hl");
const controlInputList = document.querySelectorAll("input");
controlInputList.forEach((input) => {
  input.addEventListener("input", changeStyle);
});
function changeStyle(e) {
  if (e.target.id === "spacing") {
    imgContainer.style.border = `${colorControl.value} ${e.target.value}px solid`;
  }
  if (e.target.id === "blur") {
    imgContainer.style.filter = `blur(${e.target.value}px)`;
  }
  if (e.target.id === "base") {
    imgContainer.style.border = `${e.target.value} ${spacingControl.value}px solid`;
    hl.style.color = `${colorControl.value}`;
  }
}
<hrml>)的偽類:root,並以三個 input 的 id 當作變數名稱、value 當作初始值設定。:root {
  --spacing: 10px;
  --blur: 0px;
  --base: #ffc600;
}
題外話:在使用var()時,後面可以帶入好幾個參數當作備用值,當第一個參數無效時,CSS則會自動套用第二個參數當作樣式顯示...以此類推,甚至可以寫成這樣「var(--a,var(--b,var(--c,red))」。
.hl {
  color: var(--base);
}
img {
  border: var(--spacing) var(--base) solid;
  filter: blur(var(--blur));
}
(1)使用querySelectorAll()先取得所有的 input 元素節點並把它存放於 controlInputList 變數中。
(2)以 controlInputList 使用forEach()將每個 input 節點都新增一個針對HTMLElement: input event的事件監聽器,當 input 值有變更時都會執行函式 changeStyle。
(3)函式 changeStyle:
_ 宣告一個代表單位的變數,如果 input 本身HTMLElement: dataset property有自定義 sizing 那就引用單位否則就是一個空字串。
_ document.documentElement 其實等於 document.querySelector("html")
Element.style.setProperty(propertyName, "value")其實也等於 Element.style.propertyName = "value"
//改用 CSS variables
const controlInputList = document.querySelectorAll("input");
controlInputList.forEach((input) => {
  input.addEventListener("input", changeStyle);
});
function changeStyle(e) {
  const unit = e.target.dataset.sizing ?? "";
  document.documentElement.style.setProperty(
    `--${e.target.id}`,
    `${e.target.value}${unit}`
  );
  //document.documentElement.style[`--${e.target.id}`] = `${e.target.value}${unit}`;
}